﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using AddressBookDev.Filters;
using AddressBookDev.Models;
using AddressBookDev.ViewModels;
using WebMatrix.WebData;

namespace AddressBookDev.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Contacts List";
            ContactsListViewModel contacts = new ContactsListViewModel
            {
                Contacts = ContactsModel.GetContacts(WebSecurity.CurrentUserId)
            };
            return View(contacts);
        }

        public ActionResult Contact(int id = -1)
        {
            ContactViewModel contact = ContactsModel.GetContact(id);
            ViewBag.Message = contact != null ? "Update contact" : "Add Contact";
            if (contact == null)
            {
                contact = new ContactViewModel();
            }

            return View(contact);
        }

        public ActionResult SaveContact(ContactViewModel contact)
        {
            if (ModelState.IsValid)
            {
                if (contact != null)
                {
                    contact.UserId = WebSecurity.CurrentUserId;
                    ContactsModel.SaveContact(contact);
                    string pictureFolder = Utilities.File.GetPath(Server.MapPath("~/Content"),
                                        WebConfigurationManager.AppSettings["ContactPicturesFolder"],
                                        WebSecurity.CurrentUserName, contact.Name + "_" + contact.Id);
                    string serverPath = !string.IsNullOrEmpty(contact.ServerPath)
                                            ? contact.ServerPath
                                            : !string.IsNullOrEmpty(contact.Picture)
                                            ? Path.Combine(pictureFolder, contact.Picture.Split('/').Last()) : null;
                    if (!string.IsNullOrEmpty(serverPath))
                    {
                        if (System.IO.File.Exists(serverPath))
                        {
                            try
                            {
                                using (
                                    Image image = Image.FromFile(
                                        serverPath))
                                {
                                    string pictureName = Guid.NewGuid() + Path.GetExtension(serverPath);
                                    string pictureFilePath = Path.Combine(pictureFolder, pictureName);
                                    Image croppedImage = (contact.PicX > 0 || contact.PicY > 0 ||
                                                          contact.PicWidth < image.Width ||
                                                          contact.PicHeight < image.Height)
                                        ? Utilities.Images.CropBitmap(image, contact.PicX, contact.PicY,
                                            contact.PicWidth,
                                            contact.PicHeight)
                                        : image;
                                    croppedImage.Save(pictureFilePath, ImageFormat.Jpeg);
                                    contact.Picture =
                                        Utilities.Images.CreateImageUrl(
                                            WebConfigurationManager.AppSettings["ContactPicturesFolder"],
                                            WebSecurity.CurrentUserName, contact.Name + "_" + contact.Id, pictureName);
                                    ContactsModel.SetContactPicture(contact.Id, contact.Picture, croppedImage.Width, croppedImage.Height);
                                }
                                if (string.IsNullOrEmpty(contact.ServerPath))
                                {
                                    System.IO.File.Delete(serverPath);
                                }
                                string tempFolder = Utilities.File.GetPath(Server.MapPath("~/Content"),
                                                                           WebConfigurationManager.AppSettings[
                                                                               "ContactPicturesFolder"],
                                                                           WebSecurity.CurrentUserName);
                                string[] tempPics = Directory.GetFiles(tempFolder);
                                foreach (string filePath in tempPics)
                                {
                                    System.IO.File.Delete(filePath);
                                }
                            }
                            catch (Exception)
                            {
                                ModelState.AddModelError("PictureFile",
                                    "Contacts was saved but there was a problem saving the picture");
                            }
                        }
                    }
                }
            }

            if (ModelState.IsValid)
            {
                return RedirectToAction("Index");
            }

            return View("Contact", contact);
        }

        
        public ActionResult GetContactsFiltered(string term)
        {
            var filteredContacts = ContactsModel.GetContactsFiltered(WebSecurity.CurrentUserId, term)
                .Select(c => new Dictionary<string, object> {{"label", c.Name}, {"id", c.Id}});
            return Json(filteredContacts, JsonRequestBehavior.AllowGet);
        }

        public ActionResult PreviewImage(HttpPostedFileBase pictureFile)
        {
            string erroMessage = null;
            string pictureurl = null;
            string picturepath = null;
            int width = 0, height = 0;
            if (pictureFile != null && pictureFile.ContentLength > 0)
            {
                try
                {
                    using (
                        Image image = Image.FromStream(
                            pictureFile.InputStream, true, true))
                    {
                        string pictureName = Guid.NewGuid() + Path.GetExtension(pictureFile.FileName);
                        string pictureFolder = Utilities.File.GetPath(Server.MapPath("~/Content"),
                            WebConfigurationManager.AppSettings["ContactPicturesFolder"],
                            WebSecurity.CurrentUserName);
                        picturepath = Path.Combine(pictureFolder, pictureName);
                        Image resizedImage = Utilities.Images.ResizeImage(image, Utilities.Images.GetContactImageSize());
                        resizedImage.Save(picturepath, ImageFormat.Jpeg);
                        width = resizedImage.Width;
                        height = resizedImage.Height;
                        pictureurl = Utilities.Images.CreateImageUrl(WebConfigurationManager.AppSettings["ContactPicturesFolder"], WebSecurity.CurrentUserName, pictureName);
                    }
                }
                catch (Exception)
                {
                    erroMessage = "Please upload a valid image";
                }
            }
            return Json(new Dictionary<string, object> { { "path", pictureurl }, { "width", width }, { "height", height }, { "serverpath", picturepath }, { "error", erroMessage } },
                        JsonRequestBehavior.AllowGet);
        }

        public ActionResult DeleteContacts(IEnumerable<string> fordelete)
        {
            foreach (string s in fordelete)
            {
                int id;
                if (int.TryParse(s, out id))
                {
                    ContactViewModel contact = ContactsModel.GetContact(id);
                    if (ContactsModel.DeleteContact(id))
                    {
                        string contactFolder = Utilities.File.GetPath(Server.MapPath("~/Content"),
                                        WebConfigurationManager.AppSettings["ContactPicturesFolder"],
                                        WebSecurity.CurrentUserName, contact.Name + "_" + id);
                        Utilities.Images.DeleteContactImage(contactFolder, id);
                    }
                }
            }
            return RedirectToAction("Index");
        }
    }
}
